const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../../utils/config.js'
import {
  validateEmoji,
  validateSpecial
} from '../../../../../utils/validate.js'
import {
  reqSpaceEdit,
  reqSpaceImage,
  reqDeviceBySpaceId,
  reqDeviceByImei,
  reqDeviceAdd,
  reqDeviceUnBind,
  reqAlarmReceiverList,
  reqReceiverSpaceAdd,
  reqAlarmReceiverBySpaceId
} from '../../../../../request/api'
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    spaceInfo: {
      type: Object,
      value: {},
    }
  },


  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离

    form: {
      id: '',
      orgId: ''
    },
    // 接警人开始
    showPeopleCall: false,
    alarmReceiverList: [],
    alarmPage: 1,
    alarmIsNextPage: true,
    alarmReceiverArr: [], //最终提交值id集合
    selAlarmReceiverArr: [], //展示渲染页面
    alarmReceiverIdList1: [],
    alarmReceiverIdList2: [],
    alarmReceiverIdList3: [],
    alarmReceiverIdList4: [],

    expanded: true,
    level: 1,
    levelList: [{
        value: 1,
        name: "一级",
      },
      {
        value: 2,
        name: "二级",
      },
      {
        value: 3,
        name: "三级",
      },
      {
        value: 4,
        name: "四级",
      },
    ],
    // 接警人结束
    disabledBtn: false,
  },


  observers: {
    'spaceInfo': function (newVal) {
      this.setData({
        'form.id': newVal.id,
        'form.orgId': item.orgId,
      })
      if (newVal.id) {
        this.AlarmReceiverBySpaceId()
        this.getAlarmReceiverList() //获取接警人列表
      }
    }
  },
  methods: {

    // -----------------接警人开始----------------
    // 空间id获取接警人列表
    async AlarmReceiverBySpaceId() {
      const res = await reqAlarmReceiverBySpaceId(this.data.form.id)
      let {
        rows
      } = res.data
      if (rows && rows.length) {
        rows.sort((a, b) => a.level - b.level)
        this.setData({
          selAlarmReceiverArr: rows
        })
      } else {
        this.setData({
          selAlarmReceiverArr: []
        })
      }
    },

    //展开/收缩接警人
    togglePanel() {
      this.setData({
        expanded: !this.data.expanded
      });
    },

    // 点击展示接警人弹窗
    async clickShowPeopleCall(e) {
      // console.log(e.currentTarget.dataset.value);
      // const res = await reqAlarmReceiverBySpaceId(this.data.form.id)
      // 复选框渲染已有的接警人
      // let {
      //   rows
      // } = res.data;
      // console.log(rows);
      // console.log(this.data.alarmReceiverArr.length);
      // 只有第一次进来才选中状态
      // if (rows.length != this.data.alarmReceiverArr.length) {
      let rows = this.data.selAlarmReceiverArr
      rows.forEach((result, index) => {
        console.log(result.level == e.currentTarget.dataset.value);
        // 勾选对应级别的接警人
        if (result.level == e.currentTarget.dataset.value) {
          const checkbox = this.selectComponent(`.checkboxes-${result.id}`);
          checkbox.toggle();
        }
      })
      // }
      // 级别禁用
      let arr = []
      if (e.currentTarget.dataset.value == 1) {
        arr = [...this.data.alarmReceiverIdList2, ...this.data.alarmReceiverIdList3, ...this.data.alarmReceiverIdList4]
      } else if (e.currentTarget.dataset.value == 2) {
        arr = [...this.data.alarmReceiverIdList1, ...this.data.alarmReceiverIdList3, ...this.data.alarmReceiverIdList4]
      } else if (e.currentTarget.dataset.value == 3) {
        arr = [...this.data.alarmReceiverIdList2, ...this.data.alarmReceiverIdList1, ...this.data.alarmReceiverIdList4]
      } else if (e.currentTarget.dataset.value == 4) {
        arr = [...this.data.alarmReceiverIdList2, ...this.data.alarmReceiverIdList3, ...this.data.alarmReceiverIdList1]
      }
      // console.log(arr);
      let list = this.data.alarmReceiverList.map(item => {
        item.disabled = false;
        arr.forEach(item2 => {
          if (item.id == item2.id) {
            item.disabled = true;
          }
        })
        return item
      })
      // console.log(list);
      this.setData({
        showPeopleCall: true,
        valueInfo: e.currentTarget.dataset.value,
        alarmReceiverList: list, //级别禁用
      })
    },
    // 点击关闭接警人弹窗
    async closePeopleCall() {
      //   清空选中的状态
      this.data.alarmReceiverArr.forEach((result, index) => {
        console.log(result);
        const checkbox = this.selectComponent(`.checkboxes-${result}`);
        checkbox.toggle();
      })

      let list = this.data.alarmReceiverList.map(item => {
        item.disabled = false;
        return item
      })
      this.setData({
        showPeopleCall: false,
        alarmReceiverList: list, //取消禁用
      })
    },
    //接警人新增
    async receiverSpaceAddFun() {
      let {
        selAlarmReceiverArr,
      } = this.data

      let alarmReceiverIdList1 = []
      let alarmReceiverIdList2 = []
      let alarmReceiverIdList3 = []
      let alarmReceiverIdList4 = []
      selAlarmReceiverArr.forEach((item) => {
        switch (item.level) {
          case 1:
            alarmReceiverIdList1.push(item.id)
            break
          case 2:
            alarmReceiverIdList2.push(item.id)
            break
          case 3:
            alarmReceiverIdList3.push(item.id)
            break
          case 4:
            alarmReceiverIdList4.push(item.id)
            break
          default:
            return
        }
      })
      if (alarmReceiverIdList1.length > 6) return showMsg("一级接警人最多设置6个")
      if (alarmReceiverIdList2.length > 6) return showMsg("二级接警人最多设置6个")
      if (alarmReceiverIdList3.length > 6) return showMsg("三级接警人最多设置6个")
      if (alarmReceiverIdList4.length > 6) return showMsg("四级接警人最多设置6个")
      const res = await reqReceiverSpaceAdd({
        spaceId: this.data.form.id,
        alarmReceiverIdList1,
        alarmReceiverIdList2,
        alarmReceiverIdList3,
        alarmReceiverIdList4,
      })
      if (res.code != 20000) return showMsg(res.message);
    },

    /**
     * @name: 获取接警人列表
     * @return {*}
     */
    async getAlarmReceiverList() {
      let params = {
        orgId: this.data.form.orgId ,
        userId: app.globalData.userId,
        roleName: app.globalData.rolename,
      }
      const res = await reqAlarmReceiverList(this.data.alarmPage, 99, params)
      if (res.code !== 20000) return showMsg(res.message, "error")
      let {
        rows
      } = res.data
      console.log(rows);
      if (this.data.alarmPage === 1) {
        this.setData({
          alarmReceiverList: rows,
          alarmIsNextPage: true
        })
      } else if (this.data.alarmPage > 1 && rows.length) {
        this.setData({
          alarmReceiverList: this.data.alarmReceiverList.concat(rows),
          alarmIsNextPage: true
        })
      } else if (this.data.alarmPage > 1 && !rows.length) {
        showMsg('已经到底啦~')
        this.setData({
          alarmIsNextPage: false
        })
      }
      if (this.data.showPeopleCall) {
        this.clickShowPeopleCall()
      }
    },

    // 滚动到底部触发
    alarmReceiverLower() {
      if (!this.data.alarmIsNextPage) return
      this.setData({
        alarmPage: this.data.alarmPage + 1,
      })
      this.getAlarmReceiverList()
    },

    levelChange(event) {
      this.setData({
        level: event.detail,
      });
    },
    // 获取alarmReceiverArr的值
    deviceChange(event) {
      this.setData({
        alarmReceiverArr: event.detail
      })
      // console.log(this.data.alarmReceiverArr,"alarmReceiverArr")
    },
    // 点击获取alarmReceiverArr的值
    deviceToggle(event) {
      const {
        id
      } = event.currentTarget.dataset;
      this.checkboxChange(id)
    },
    // 复选框变化渲染
    checkboxChange(id) {
      console.log(id);
      const checkbox = this.selectComponent(`.checkboxes-${id}`);
      checkbox.toggle();
    },

    // 删除某个接警人
    deleteAlarmReceiver(e) {
      const {
        id,
        value
      } = e.currentTarget.dataset;

      let {
        alarmReceiverArr,
        selAlarmReceiverArr
      } = this.data
      alarmReceiverArr.forEach((item, index) => {
        if (item.id === id) {
          alarmReceiverArr.splice(index, 1)
        }
      })
      selAlarmReceiverArr.forEach((item, index) => {
        if (item.id === id) {
          selAlarmReceiverArr.splice(index, 1)
        }
      })
      this.setData({
        alarmReceiverArr,
        selAlarmReceiverArr
      })
      this.checkboxChange(id)
      this.receiverSpaceAddFun() //接警人新增
    },
    // 确定选择接警人
    async confirmPeopleCall() {
      let {
        alarmReceiverArr,
      } = this.data
      // if (alarmReceiverArr.length > 6) return showMsg("接警人最多设置6个")
      const res = await reqReceiverSpaceAdd({
        spaceId: this.data.form.id,
        alarmReceiverIdList1: this.data.valueInfo == 1 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList1.map(item => item.id),
        alarmReceiverIdList2: this.data.valueInfo == 2 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList2.map(item => item.id),
        alarmReceiverIdList3: this.data.valueInfo == 3 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList3.map(item => item.id),
        alarmReceiverIdList4: this.data.valueInfo == 4 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList4.map(item => item.id),
      })
      if (res.code != 20000) return showMsg(res.message);
      // await this.receiverSpaceAddFun()
      await this.closePeopleCall() //关闭弹窗
      this.AlarmReceiverBySpaceId() // 空间id获取接警人列表
    },
  }
})